package containers;

import java.util.*;

public class SimpleHashMap<K,V> extends AbstractMap<K,V> {
    static final int size = 997;

    @SuppressWarnings("unchecked")
    LinkedList<MapEntry<K,V>>[] buckets = new LinkedList[size];

    @Override
    public V get(Object key) {
        int index = Math.abs(key.hashCode()) % size;
        if (buckets[index] == null) return null;
        for (MapEntry<K,V> iPair : buckets[index])
            if (iPair.getKey().equals(key))
                return iPair.getValue();
        return null;
    }

    @Override
    public V put(K key, V value) {
        V oldValue = null;
        int index = Math.abs(key.hashCode()) % size;
        if (buckets[index] == null){
            buckets[index] = new LinkedList<MapEntry<K,V>>();
        }
        LinkedList<MapEntry<K,V>> bucket = buckets[index];
        MapEntry<K,V> pair = new MapEntry<K, V>(key,value);
        boolean found = false;
        ListIterator<MapEntry<K,V>> ite = bucket.listIterator();
        while (ite.hasNext()){
            MapEntry<K,V> ipair = ite.next();
            if (ipair.getKey().equals(key)){
                oldValue = ipair.getValue();
                ite.set(ipair);
                found = true;
                break;
            }
        }
        if (!found){
            buckets[index].add(pair);
        }
        return oldValue;
    }

    @Override
    public Set<Entry<K, V>> entrySet() {
        Set<Map.Entry<K,V>> set = new HashSet<Entry<K, V>>();
        for (LinkedList<MapEntry<K,V>> bucket : buckets){
            if (bucket == null) continue;
            for (MapEntry<K,V> mpair : bucket){
                set.add(mpair);
            }
        }
        return set;
    }

    public static void main(String[] args){
        SimpleHashMap<String,String> m = new SimpleHashMap<String, String>();

    }
}
